<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path: './'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开 -->
        <el-table-column type="expand">
          <template v-slot="role">
            <el-row :class="['bdbottom', idx1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, idx1) in role.row.children" :key="item1.id" closable @close="removePermission(role.row, item1.id)">
              <!-- 一级权限 -->
              <el-col :span="5">
                <span>
                  <el-tag closable @close="removePermission(role.row, item2.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </span>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 嵌套渲染二级权限 -->
                <el-row :class="[idx2===0?'':'bdtop', 'vcenter']" v-for="(item2, idx2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removePermission(role.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="(item3) in item2.children" type="warning" :key="item3.id" closable @close="removePermission(role.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="slotProps">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="primary" icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="primary" icon="el-icon-setting" @click="showAssignPermissionDialog(slotProps.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="assignPermissionDialogVisible" @close="assignPermissionDialogClosed">
      <template>
        <el-tree :data="permissionList" :props="treeProps" show-checkbox node-key="id"
          default-expand-all :default-checked-keys="defaultKeys" ref="treeRef"></el-tree>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignPermissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePermissions">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      assignPermissionDialogVisible: false,
      permissionList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defaultKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    async removePermission(role, pId) {
      const confirmResult = await this.$confirm('是否删除该权限？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // confrim / cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${pId}`)
      if (res.meta.statust !== 200) {
        this.$message.error('删除角色权限失败')
      }
      role.children = res.data
      this.$message.success('删除角色权限成功')
    },
    async showAssignPermissionDialog(role) {
      // 获取全部权限数据
      const { data: res } = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }

      this.getLeadKeys(role, this.defaultKeys)

      this.permissionList = res.data
      this.assignPermissionDialogVisible = true

      // 分配权限用当前角色id保持
      this.roleId = role.id
    },
    // 获取角色下所有第三级权限
    getLeadKeys(node, arr) {
      // 当递归到达第三级
      if (!node.children) {
        // 存入节点id
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeadKeys(item, arr)
      })
    },
    assignPermissionDialogClosed() {
      // 关闭后清空当前角色的已选权限
      this.defaultKeys = []
    },
    async updatePermissions() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })

      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }

      this.$message.success('分配权限成功')
      this.getRoleList()
      this.assignPermissionDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eeeeee;
}
.bdbottom {
  border-bottom: 1px solid #eeeeee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
